//
//  HomeVC.m
//  Project
//
//  Created by 冯东辉 on 2018/9/13.
//  Copyright © 2018年 FengDongHui. All rights reserved.
//

#import "HomeVC.h"
#import "SDCycleScrollView.h"
#import "ModuleView.h"
#import "CityBtn.h"
#import "SearchVC.h"
#import "CityTableView.h"
#import "ModuleListVC.h"
#import "ModuleSsListVC.h"
#import "ModuleDbListVC.h"

@interface HomeVC () <ModuleBtnDelegate, UIGestureRecognizerDelegate, CityChooseCallBack>

// 权限数据
@property (nonatomic, strong) NSArray *module_data;
@property (nonatomic, strong) NSMutableArray *result_module_data;
// 城市数据
@property (nonatomic, strong) NSArray *city_data;
// 城市名称
@property (nonatomic, strong) NSString *cityName;

// 头部城市按钮
@property (nonatomic, strong) CityBtn *cityBtn;
// 搜索
@property (nonatomic, strong) UIButton *searchBtn;
@property (nonatomic, strong) UIImageView *searchImage;

// 轮播图
@property (nonatomic, strong) SDCycleScrollView *cycleView;

// 权限视图
@property (nonatomic, strong) ModuleView *moduleV;

// 短板指标小红点
@property (nonatomic, strong) UILabel *redCountL;

// 城市展示图
@property (nonatomic, strong) UIView *cityBaseV;
@property (nonatomic, strong) CityTableView *cityTable;

@end

@implementation HomeVC

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.view.backgroundColor = UICOLOR_HEX(0xffffffff);
    
    NSDictionary *user_data = [[NSUserDefaults standardUserDefaults] objectForKey:USER_INFO_CITY];
    _cityName = [NSString stringWithFormat:@"%@", [user_data objectForKey:@"cityName"]];
    
    [self creatResultData];
    
    // 头部视图
    [self setHeadView];
    
    // 轮播图
    [self setCycScrollView];
    
    // 权限视图
    [self setModuleView];
    
    // 底部视图
    [self setBottomView];
    
    [self getModuleData];
}

- (void)didReceiveMemoryWarning {
    
    [super didReceiveMemoryWarning];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    [_cycleView adjustWhenControllerViewWillAppera];
    
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    self.navigationController.navigationBar.alpha = 0;
    [self.navigationController.navigationBar setBackgroundColor:[UIColor clearColor]];
}


#pragma mark - 维度指标和劣化个数
- (void)getModuleData {
    
    [[ProjectApi instance] getModuleDataWithCityName:_cityName callBack:^(NetModel *object) {
        
        if (object.isSuccessed) {
            
            [SVProgressHUD dismiss];
            
            self.module_data = [NSArray arrayWithArray:object.service];
            
            [self reloadRedData];
            
            [self.moduleV reloadViewWithData:self.result_module_data];
            
            NSInteger redCount = [self getDuanBanZhiBiaoCount];
            if (redCount == 0) {
                self.redCountL.hidden = YES;
            }else {
                self.redCountL.hidden = NO;
            }
            self.redCountL.text = [NSString stringWithFormat:@"%ld", redCount];
        }
    }];
}

#pragma mark - 头部视图
- (void)setHeadView {
    
    UIView *headV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, GET_SCREEN_WIDTH(), SafeAreaTopHeight)];
    headV.backgroundColor = Base_color;
    [self.view addSubview:headV];
    
    CGFloat cityWidth = [_cityName length]*16;
    
    _cityBtn = [[CityBtn alloc] initWithFrame:CGRectMake(10, SafeAreaTopHeight-7-30, 8+15+5+cityWidth, 30)];
    [_cityBtn setImage:[UIImage imageNamed:@"home_city"] forState:UIControlStateNormal];
    [_cityBtn setTitle:_cityName forState:UIControlStateNormal];
    [_cityBtn setTitleColor:UICOLOR_HEX(0xffffffff) forState:UIControlStateNormal];
    _cityBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [_cityBtn addTarget:self action:@selector(showAllCity) forControlEvents:UIControlEventTouchUpInside];
    [headV addSubview:_cityBtn];
    
    _searchBtn = [[UIButton alloc] initWithFrame:CGRectMake(_cityBtn.right, SafeAreaTopHeight-7-30, GET_SCREEN_WIDTH()-10-_cityBtn.right, 30)];
    _searchBtn.backgroundColor = UICOLOR_HEX(0xffffffff);
    _searchBtn.layer.cornerRadius = 5;
    _searchBtn.layer.borderColor = UICOLOR_HEX(0xffe0e0e0).CGColor;
    _searchBtn.layer.borderWidth = 1.0f;
    [_searchBtn setTitle:@"请输入关键字搜索" forState:UIControlStateNormal];
    [_searchBtn setTitleColor:UICOLOR_HEX(0xff666666) forState:UIControlStateNormal];
    _searchBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    _searchBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -11, 0, 11);
    [_searchBtn addTarget:self action:@selector(pushSearchVC) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_searchBtn];
    
    _searchImage = [[UIImageView alloc] initWithFrame:CGRectMake(_searchBtn.width-16-7, (_searchBtn.height-15)/2.0f, 16, 15)];
    _searchImage.image = [UIImage imageNamed:@"home_search"];
    [_searchBtn addSubview:_searchImage];
}

#pragma mark - 轮播图
- (void)setCycScrollView {
    
    _cycleView = [[SDCycleScrollView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight, GET_SCREEN_WIDTH(), GET_SCREEN_WIDTH()*2/5.0f)];
    _cycleView.autoScrollTimeInterval = 5;
    _cycleView.showPageControl = YES;
    _cycleView.pageControlBottomOffset = 0;
    _cycleView.localizationImageNamesGroup = @[@"banner1", @"banner2", @"banner3", @"banner4"];
    _cycleView.bannerImageViewContentMode = UIViewContentModeScaleAspectFill;
    [self.view addSubview:_cycleView];
}

#pragma mark - 权限视图
- (void)setModuleView {
    
    CGFloat height = GET_SCREEN_HEIGHT()-SafeAreaBottomHeight-_cycleView.bottom-60;
    
    _moduleV = [[ModuleView alloc] initWithFrame:CGRectMake(0, _cycleView.bottom, GET_SCREEN_WIDTH(), height) data:_result_module_data];
    _moduleV.backgroundColor = UICOLOR_HEX(0xffffffff);
    _moduleV.delegate = self;
    [self.view addSubview:_moduleV];
}

#pragma mark - 短板指标/实时指标
- (void)setBottomView {
    
    UIView *bottomV = [[UIView alloc] initWithFrame:CGRectMake(0, _moduleV.bottom, GET_SCREEN_WIDTH(), 60)];
    [self.view addSubview:bottomV];
    
    // 短板指标
    UIButton *dbBtn = [[UIButton alloc] initWithFrame:CGRectMake(20, 10, (GET_SCREEN_WIDTH()-20*3)/2.0f, 30)];
    [dbBtn.layer addSublayer:[ProjectTools setJianBianWithBenginColor:UICOLOR_HEX(0xfffc4a32) endColor:UICOLOR_HEX(0xfffbc042) frame:dbBtn.bounds cornerRadius:15]];
    [dbBtn setTitle:@"短板指标" forState:UIControlStateNormal];
    [dbBtn setTitleColor:UICOLOR_HEX(0xffffffff) forState:UIControlStateNormal];
    dbBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [dbBtn addTarget:self action:@selector(pushdbZhiBiao) forControlEvents:UIControlEventTouchUpInside];
    [bottomV addSubview:dbBtn];
    
    _redCountL = [[UILabel alloc] initWithFrame:CGRectMake(dbBtn.width-10, 0, 15, 15)];
    _redCountL.layer.cornerRadius = 7.5f;
    _redCountL.layer.masksToBounds = YES;
    _redCountL.backgroundColor = UICOLOR_HEX(0xffff6767);
    _redCountL.textColor = UICOLOR_HEX(0xffffffff);
    _redCountL.font = [UIFont systemFontOfSize:12];
    _redCountL.textAlignment = NSTextAlignmentCenter;
    NSInteger redCount = [self getDuanBanZhiBiaoCount];
    if (redCount == 0) {
        _redCountL.hidden = YES;
    }else {
        _redCountL.hidden = NO;
    }
    _redCountL.text = [NSString stringWithFormat:@"%ld", redCount];
    [dbBtn addSubview:_redCountL];
    
    // 实时指标
    UIButton *ssBtn = [[UIButton alloc] initWithFrame:CGRectMake(dbBtn.right+20, dbBtn.top, dbBtn.width, dbBtn.height)];
    [ssBtn.layer addSublayer:[ProjectTools setJianBianWithBenginColor:UICOLOR_HEX(0xff169bfa) endColor:UICOLOR_HEX(0xff9977e3) frame:ssBtn.bounds cornerRadius:15]];
    [ssBtn setTitle:@"实时指标" forState:UIControlStateNormal];
    [ssBtn setTitleColor:UICOLOR_HEX(0xffffffff) forState:UIControlStateNormal];
    ssBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [ssBtn addTarget:self action:@selector(pushssZhiBiao) forControlEvents:UIControlEventTouchUpInside];
    [bottomV addSubview:ssBtn];
}

#pragma mark - 短板指标
- (void)pushdbZhiBiao {
    
    ModuleDbListVC *dbListVc = [[ModuleDbListVC alloc] init];
    dbListVc.cityName = _cityName;
    dbListVc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:dbListVc animated:YES];
}

#pragma mark - 实时指标
- (void)pushssZhiBiao {

    ModuleSsListVC *ssListVc = [[ModuleSsListVC alloc] init];
    ssListVc.cityName = _cityName;
    ssListVc.type = @"1";
    ssListVc.h = @"24";
    ssListVc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:ssListVc animated:YES];
}

#pragma mark - 创建原始数据
- (void)creatResultData {
    
    [_result_module_data removeAllObjects];
    _result_module_data = nil;
    
    _result_module_data = [NSMutableArray arrayWithCapacity:10];
    
    NSDictionary *dic1 = @{@"count":@"0", @"dim_Name":@"业务发展", @"sdim_ID":@"B01"};
    NSDictionary *dic2 = @{@"count":@"0", @"dim_Name":@"无线接入", @"sdim_ID":@"B04"};
    NSDictionary *dic3 = @{@"count":@"0", @"dim_Name":@"无线覆盖", @"sdim_ID":@"B05"};
    NSDictionary *dic4 = @{@"count":@"0", @"dim_Name":@"无线语音业务", @"sdim_ID":@"B06"};
    NSDictionary *dic5 = @{@"count":@"0", @"dim_Name":@"无线数据业务", @"sdim_ID":@"B03"};
    NSDictionary *dic6 = @{@"count":@"0", @"dim_Name":@"无线网络结构", @"sdim_ID":@"B07"};
    NSDictionary *dic7 = @{@"count":@"0", @"dim_Name":@"基站退服", @"sdim_ID":@"B02"};
    NSDictionary *dic8 = @{@"count":@"0", @"dim_Name":@"宽带业务", @"sdim_ID":@"B08"};
    NSDictionary *dic9 = @{@"count":@"0", @"dim_Name":@"魔百盒业务", @"sdim_ID":@"B09"};
    NSDictionary *dic10 = @{@"count":@"0", @"dim_Name":@"传输网络", @"sdim_ID":@"B11"};
    
    [_result_module_data addObject:dic1];
    [_result_module_data addObject:dic2];
    [_result_module_data addObject:dic3];
    [_result_module_data addObject:dic4];
    [_result_module_data addObject:dic5];
    [_result_module_data addObject:dic6];
    [_result_module_data addObject:dic7];
    [_result_module_data addObject:dic8];
    [_result_module_data addObject:dic9];
    [_result_module_data addObject:dic10];
    
}

#pragma mark - 小红点数据匹配
- (void)reloadRedData {
    
    for (int i = 0; i < [_result_module_data count]; i++) {
        
        NSMutableDictionary *resultDic = [NSMutableDictionary dictionaryWithDictionary:_result_module_data[i]];
        
        NSString *result_sdim_id = resultDic[@"sdim_ID"];
        
        for (int y = 0; y < [_module_data count]; y++) {
            
            NSDictionary *moduleDic = _module_data[y];
            NSString *module_sdim_id = moduleDic[@"sdim_ID"];
            
            if ([result_sdim_id isEqualToString:module_sdim_id]) {
                
                NSInteger module_count = [moduleDic[@"count"] integerValue];
                
                if (module_count > 0) {
                    [resultDic setValue:[NSString stringWithFormat:@"%ld", module_count] forKey:@"count"];
                    [_result_module_data removeObjectAtIndex:i];
                    [_result_module_data insertObject:resultDic atIndex:i];
                }
                break;
            }
        }
    }
}

#pragma mark - 计算短板指标数量
- (NSInteger)getDuanBanZhiBiaoCount {
    
    NSInteger allCount = 0;
    
    for (NSDictionary *dic in _result_module_data) {
        
        NSInteger count = [dic[@"count"] integerValue];
        
        allCount += count;
    }
    
    return allCount;
}

#pragma mark - 展示城市选择
- (void)showAllCity {
    
    _city_data = [[NSUserDefaults standardUserDefaults] objectForKey:USER_CITY_DATA];
    
    if (_city_data && [_city_data count] > 0) {
        
        [self creatCityChooseView];
        
    }else {
        
        // 获取用户ID拥有的地市权限
        [SVProgressHUD showWithStatus:@"加载中..."];
        
        [[ProjectApi instance] getUserCityDataCallBack:^(NetModel *object) {
            
            if (object.isSuccessed) {
                
                self.city_data = [NSArray arrayWithArray:object.service];
                
                [[NSUserDefaults standardUserDefaults] setObject:self.city_data forKey:USER_CITY_DATA];
                [[NSUserDefaults standardUserDefaults] synchronize];
                
                [SVProgressHUD dismiss];
                
                [self creatCityChooseView];
                
            }else {
                
                [SVProgressHUD showErrorWithStatus:@"地址加载失败"];
                [SVProgressHUD dismissWithDelay:1.5f];
            }
        }];
    }
}

#pragma mark - 创建城市选择视图
- (void)creatCityChooseView {
    
    _cityBaseV = [[UIView alloc] initWithFrame:CGRectMake(0, 0, GET_SCREEN_WIDTH(), GET_SCREEN_HEIGHT())];
    _cityBaseV.backgroundColor = [UIColor clearColor];
    [self.view.window addSubview:_cityBaseV];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hidCityBaseView)];
    tap.delegate = self;
    [_cityBaseV addGestureRecognizer:tap];
    
    CGFloat table_height = 40*[_city_data count];
    
    if (table_height > GET_SCREEN_HEIGHT()*2/3.0f) {
        
        table_height = GET_SCREEN_HEIGHT()*2/3.0f;
    }
    
    _cityTable = [[CityTableView alloc] initWithFrame:CGRectMake(_cityBtn.left-5, SafeAreaTopHeight, _cityBtn.width+5, table_height) style:UITableViewStylePlain data:_city_data];
    _cityTable.city_delegate = self;
    [_cityBaseV addSubview:_cityTable];
}

#pragma mark - 隐藏城市展示图
- (void)hidCityBaseView {
    
    _cityBaseV.hidden = YES;
}

#pragma mark - 城市选择回调
- (void)cityChooseCallBack:(NSDictionary *)city_dic {
    
    // 隐藏展示图
    [self hidCityBaseView];
    
    // 选择的城市名称
    NSString *chooseCityName = [NSString stringWithFormat:@"%@", city_dic[@"cityname"]];
    
    if ([chooseCityName isEqualToString:_cityName]) {
        return;
    }
    
    [self getModuleDataWithCityName:chooseCityName];
}

#pragma mark - 维度指标和劣化个数
- (void)getModuleDataWithCityName:(NSString *)chooseCityName {
    
    [[ProjectApi instance] getModuleDataWithCityName:chooseCityName callBack:^(NetModel *object) {
        
        if (object.isSuccessed) {
            
            [self getModuleDataSuccessdHandle:object.service chooseCityName:chooseCityName];
            
        }else {
            
            [SVProgressHUD showErrorWithStatus:@"网络连接失败"];
            [SVProgressHUD dismissWithDelay:1.5f];
        }
    }];
}

/**
 * 维度指标和劣化个数获取成功处理
 */
- (void)getModuleDataSuccessdHandle:(NSArray *)json_arr chooseCityName:(NSString *)chooseCityName {
    
    _cityName = chooseCityName;
    _module_data = json_arr;
    
    [self creatResultData];
    [self reloadRedData];
    
    CGFloat cityWidth = [_cityName length]*16;
    
    _cityBtn.frame = CGRectMake(10, SafeAreaTopHeight-7-30, 8+15+5+cityWidth, 30);
    [_cityBtn setTitle:_cityName forState:UIControlStateNormal];
    
    _searchBtn.frame = CGRectMake(_cityBtn.right, SafeAreaTopHeight-7-30, GET_SCREEN_WIDTH()-10-_cityBtn.right, 30);
    
    _searchImage.frame = CGRectMake(_searchBtn.width-16-7, (_searchBtn.height-15)/2.0f, 16, 15);
    
    [_moduleV reloadViewWithData:_result_module_data];
    
    NSInteger redCount = [self getDuanBanZhiBiaoCount];
    if (redCount == 0) {
        _redCountL.hidden = YES;
    }else {
        _redCountL.hidden = NO;
    }
    _redCountL.text = [NSString stringWithFormat:@"%ld", redCount];
}

#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    
    //判断如果点击的是tableView的cell，就把手势给关闭了
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        
        return NO;
    }
    
    return YES;
}

#pragma mark - 进入搜索页面
- (void)pushSearchVC {
    
    SearchVC *searchVC = [[SearchVC alloc] init];
    searchVC.cityName = _cityName;
    searchVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:searchVC animated:YES];
}

#pragma mark - 权限点击回调
/**
 * @param dim_Name 名称
 * @param sdim_ID  ID
 */
- (void)touchModuleBtnCallBack:(NSString *)dim_Name
                          note:(NSString *)sdim_ID {
    
    NSLog(@"dim_name : %@, sdim_id : %@", dim_Name, sdim_ID);
    
    ModuleListVC *listVC = [[ModuleListVC alloc] init];
    listVC.cityName = _cityName;
    listVC.moduleName = dim_Name;
    listVC.type = @"1";
    listVC.sdim_ID = sdim_ID;
    listVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:listVC animated:YES];
}

@end
